<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>增强版WebSocket测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .connected { background-color: #d4edda; color: #155724; }
        .disconnected { background-color: #f8d7da; color: #721c24; }
        .reconnecting { background-color: #fff3cd; color: #856404; }
        .message-area {
            height: 300px;
            border: 1px solid #ddd;
            padding: 10px;
            overflow-y: auto;
            background-color: #f8f9fa;
            margin: 10px 0;
            font-family: monospace;
            font-size: 12px;
        }
        .input-group {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }
        input[type="text"] {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin: 20px 0;
        }
        .stat-item {
            background-color: #e9ecef;
            padding: 10px;
            border-radius: 4px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>增强版WebSocket连接测试</h1>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="stats">
            <div class="stat-item">
                <div class="stat-value" id="messageCount">0</div>
                <div>消息数量</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" id="reconnectCount">0</div>
                <div>重连次数</div>
            </div>
            <div class="stat-item">
                <div class="stat-value" id="connectionTime">0s</div>
                <div>连接时长</div>
            </div>
        </div>
        
        <div class="input-group">
            <button id="connectBtn" onclick="connect()">连接</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开</button>
            <button onclick="clearMessages()">清空消息</button>
        </div>
        
        <div class="input-group">
            <input type="text" id="messageInput" placeholder="输入消息..." onkeypress="handleKeyPress(event)">
            <button onclick="sendMessage()" id="sendBtn" disabled>发送</button>
            <button onclick="sendTestMessages()">发送测试消息</button>
        </div>
        
        <div id="messages" class="message-area"></div>
        
        <div>
            <h3>功能特性测试</h3>
            <button onclick="testReconnect()">测试重连机制</button>
            <button onclick="testMessageQueue()">测试消息队列</button>
            <button onclick="testHeartbeat()">测试心跳检测</button>
        </div>
    </div>

    <script>
        let ws = null;
        let messageCount = 0;
        let reconnectCount = 0;
        let connectionStartTime = null;
        let connectionTimer = null;

        function updateStatus(status, className) {
            const statusEl = document.getElementById('status');
            statusEl.textContent = status;
            statusEl.className = 'status ' + className;
        }

        function addMessage(message, type = 'info') {
            const messagesEl = document.getElementById('messages');
            const timestamp = new Date().toLocaleTimeString();
            const messageEl = document.createElement('div');
            messageEl.innerHTML = `<span style="color: #666;">[${timestamp}]</span> <span style="color: ${type === 'error' ? 'red' : type === 'success' ? 'green' : 'black'};">${message}</span>`;
            messagesEl.appendChild(messageEl);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        function updateStats() {
            document.getElementById('messageCount').textContent = messageCount;
            document.getElementById('reconnectCount').textContent = reconnectCount;
            
            if (connectionStartTime) {
                const duration = Math.floor((Date.now() - connectionStartTime) / 1000);
                document.getElementById('connectionTime').textContent = duration + 's';
            }
        }

        function connect() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                return;
            }

            updateStatus('连接中...', 'reconnecting');
            
            try {
                ws = new WebSocket('ws://localhost:8080/ws');
                
                ws.onopen = function() {
                    updateStatus('已连接', 'connected');
                    addMessage('WebSocket连接已建立', 'success');
                    connectionStartTime = Date.now();
                    
                    document.getElementById('connectBtn').disabled = true;
                    document.getElementById('disconnectBtn').disabled = false;
                    document.getElementById('sendBtn').disabled = false;
                    
                    // 启动连接时长计时器
                    connectionTimer = setInterval(updateStats, 1000);
                };
                
                ws.onmessage = function(event) {
                    messageCount++;
                    addMessage('收到: ' + event.data, 'success');
                    updateStats();
                };
                
                ws.onclose = function(event) {
                    updateStatus('连接已断开', 'disconnected');
                    addMessage(`连接关闭: code=${event.code}, reason=${event.reason}`, 'error');
                    
                    document.getElementById('connectBtn').disabled = false;
                    document.getElementById('disconnectBtn').disabled = true;
                    document.getElementById('sendBtn').disabled = true;
                    
                    if (connectionTimer) {
                        clearInterval(connectionTimer);
                        connectionTimer = null;
                    }
                    
                    // 模拟自动重连
                    if (event.code !== 1000) { // 非正常关闭
                        reconnectCount++;
                        updateStats();
                        addMessage('5秒后尝试重连...', 'info');
                        setTimeout(() => {
                            if (ws.readyState === WebSocket.CLOSED) {
                                connect();
                            }
                        }, 5000);
                    }
                };
                
                ws.onerror = function(error) {
                    addMessage('WebSocket错误: ' + error, 'error');
                    updateStatus('连接错误', 'disconnected');
                };
                
            } catch (error) {
                addMessage('连接失败: ' + error.message, 'error');
                updateStatus('连接失败', 'disconnected');
            }
        }

        function disconnect() {
            if (ws) {
                ws.close(1000, 'User requested disconnect');
            }
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (message && ws && ws.readyState === WebSocket.OPEN) {
                ws.send(message);
                addMessage('发送: ' + message, 'info');
                input.value = '';
            }
        }

        function sendTestMessages() {
            const testMessages = [
                'Hello WebSocket!',
                '测试中文消息',
                JSON.stringify({type: 'test', data: 'JSON消息'}),
                '这是一条长消息：' + 'A'.repeat(100)
            ];
            
            testMessages.forEach((msg, index) => {
                setTimeout(() => {
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(msg);
                        addMessage('发送测试消息 ' + (index + 1) + ': ' + msg, 'info');
                    }
                }, index * 1000);
            });
        }

        function testReconnect() {
            addMessage('测试重连机制：强制断开连接', 'info');
            if (ws) {
                ws.close(1006, 'Test reconnect'); // 异常关闭码
            }
        }

        function testMessageQueue() {
            addMessage('测试消息队列：快速发送多条消息', 'info');
            for (let i = 1; i <= 10; i++) {
                setTimeout(() => {
                    if (ws && ws.readyState === WebSocket.OPEN) {
                        ws.send(`队列消息 ${i}`);
                    }
                }, i * 100);
            }
        }

        function testHeartbeat() {
            addMessage('心跳检测由服务器自动处理', 'info');
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
            messageCount = 0;
            updateStats();
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        // 页面加载时自动连接
        window.onload = function() {
            updateStats();
            addMessage('页面已加载，点击连接按钮开始测试', 'info');
        };
    </script>
</body>
</html>